# -*- coding: UTF-8 -*-
import re
from django.http import HttpResponseRedirect,HttpResponse
import json
import logging

class CheckLoginMiddleware(object):
    logger = logging.getLogger('free_time.roles.check_login_middleware')

    def process_request(self, request):
        """
        该函数在每个函数之前检查是否登录，若未登录，则重定向到/login/
        """
        userSession = request.session.get('login_username', False)
        print("CheckLoginMiddleware.process_request="+userSession)
        if userSession in (False, '匿名用户'):
            self.logger.warning(self,"%s尝试匿名登录...." % userSession)
            #以下是不用跳转到login页面的url白名单
            if request.path not in ('/', '/loginAction') is None:
                return HttpResponseRedirect('/login')

        if userSession == True:
            if request.path not in ('该用户模块列表') is None:
                self.logger.warning(self, "%s尝试访问无权限模块...." % userSession)
                return HttpResponse(json.dumps({'status':1, 'msg':'您没有权限访问该模块.', 'data':''}), content_type='application/json')
